#include <pthread.h>
#include <time.h>


#include "mpTimeTrigger.h"
#include "base.h"

static dLinkList *pdltEvent;
static BOOL exitSign;
static pthread_rwlockattr_t prwlockq;

int addTimeTrigger(timeTriggerEntry *tre) {

	BOOL revCode=TRUE;

	pthread_rwlock_wrlock(&prwlockq);
	if(FALSE==(revCode=addDLinkListItem(pdltEvent,"",(void *)tre))){
		logIt(LOG_ERROR,"Push item timeTriggerEntry failed");
	}
	pthread_rwlock_unlock(&prwlockq);
	return revCode;
}

triggerObject* pukeTriggeredEventObj() {

	static time_t now;
	static struct tm *ptm;

	time(&now);
	ptm=localtime(&now);


}

static BOOL loadBuiltInHolidays(){
	char *conf,*temp;
	lineInfo li;
	FILEW fwp;
	char line[MAX_LENGTH_OF_LINE];

	BOOL rev=TRUE;

	if(NULL==(conf=getConfItem("WASD_CONF"))){
		return FALSE;
	}

	sprintf(fwp.fname,"%s%s",conf,"/plugins/mpTimeTrigger/builtin.holiday");
	if(NULL==(fwp.fp=fopen(fwp.fname,"r"))){
		rev=FALSE;
	}else{

		/*read the file starting from the first line*/
		li.lineNum=1;
		while(TRUE==readLine(&fwp,line,&li)){
			getKeyAndValue(line,)
		}
	}

	return rev;
}
/*
 * The queue that contains all timeTriggers. The queue is a queue with orders. objects with
 * higher "nice" value of  will be placed in the first positions.
 */

int runTriggerEventCycle() {

	/* intialize return code*/
	int revCode=TRUE;
	exitSign = FALSE;

	if (NULL == (pdltEvent = initDLinkList())) {
		logIt(
				LOG_ERROR,
				"Initializing runTriggerEventCyle failed. Cannot malloc memories");
	}

	logIt(LOG_INFO, "TriggerEvent Component starts to work");

	/*load builtInHolidays into memory*/


	/*Initialize the rw lock*/
	if (0 != pthread_rwlockattr_init(&prwlockq)) {
		logIt(LOG_ERROR, "Initializing rw lock prwlockq failed");
		/* gnma_attention */
		revCode=FALSE;
		goto error_rev;
	}
	/*Set the scope of the lock ----this process only */
	pthread_rwlockattr_setpshared(&prwlockq, PTHREAD_PROCESS_PRIVATE);

	while (exitSign != TRUE) {

		/* Check whether it's time to puke a event.
		 *
		 */
		static time_t now, nowPlusOneMin;
		static struct tm strT,*tmTemp;

		pukeTriggeredEventObj();

		now = getUTCNow();
		/*Sleep (next time_t of next min - time_t now) seconds */

		tmTemp = localtime(&now);
		memcpy(&strT,tmTemp);
		strT.tm_min+=1;
		strT.tm_sec=0;
		nowPlusOneMin=mktime(&strT);
		sleep(nowPlusOneMin-now);
	}

	error_rev: pthread_rwlock_destroy(&prwlockq);
	return revCode;

}
